import ch.qos.logback.core.model.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@Controller
@RequestMapping("redirect:templates/productlist.html")
public class ProductController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("templates/form.html")
    public String showForm() {
        return "redirect:templates/form.html";
    }

    @PostMapping("/add")
    public String addProduct(@RequestParam("id")String  id,
                             @RequestParam("name") String name,
                             @RequestParam("description") String description,
                             @RequestParam("price") BigDecimal price,
                             @RequestParam(value = "image", required = false) MultipartFile image) {
        try {
            byte[] imageData = null;
            if (image != null && !image.isEmpty()) {
                imageData = image.getBytes();
            }
            jdbcTemplate.update("INSERT INTO product (id,name, description, price, image) VALUES (?,?, ?, ?, ?)",
                    id,name, description, price, imageData);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:templates/productlist.html";
    }
}

